package com.springboot.security.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @Author: TongRui乀
 * @Date: 2019/1/24 13:26
 * @description： Spring Security 配置
 */

@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, proxyTargetClass = true)
public class SpringSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private TestAuthenticationSuccessHandler testAuthenticationSuccessHandler;

    @Autowired
    private TestAuthenticationFailHandler testAuthenticationFailHandler;

    @Autowired
    private TestLogoutSuccessHandler testLogoutSuccessHandler;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf().disable()
            .authorizeRequests()
            // 放行下面匹配的链接
            .antMatchers("/resources/**", "/signup ", "/about", "/system/logout", "/system/login.html").permitAll()
            // 下面匹配的链接需要ADMIN角色
            .antMatchers("/admin/**").hasRole("ADMIN")
            // db 请求 需要同时拥有 ADMIN 和 DB的角色
            .antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')")
            // 剩下所有的 请求 都必须经过身份认证 也就是 login
            .anyRequest().authenticated()

            .and()
            // 基于表单认证
            .formLogin()
            // 登陆页面地址
            .loginPage("/login.html")
            // 登陆认证处理地址
            .loginProcessingUrl("/login")
            // 登陆 用户名的 参数名称
            .usernameParameter("userName")
            // 登陆用户密码的参数名称
            .passwordParameter("passWord")
            // 登陆成功处理Handler
            .successHandler(testAuthenticationSuccessHandler)
            // 登陆失败处理Handler
            .failureHandler(testAuthenticationFailHandler)
            // 登陆成功或者失败的跳转地址
            //.successForwardUrl("")
            //.failureForwardUrl("")

            .and()
            // 登出处理
            .logout()
            // 登出成功之后handler
            .logoutSuccessHandler(testLogoutSuccessHandler)
            // 删除Session
            .invalidateHttpSession(true)
            // 删除Cookie
            .deleteCookies("user");
    }


    @Bean
    PasswordEncoder getPasswordEncoder(){
        return new BCryptPasswordEncoder();
    }
}
